package com.tuomaxu.filter;

import com.tuomaxu.service.UserServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@Component
public class TokenValidate implements GlobalFilter, Ordered {

    @Autowired
    private UserServiceFeignClient userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();



        RequestPath path = request.getPath();
        System.out.println(path);
        String s = path.toString();
        /*
        /user/register
        /user/login
        /code/create
        这三个不验证token，直接放行
        其他经过网关的请求都需要验证token
         */
        if(s.contains("/user/register")||s.contains("/user/login")||s.contains("/code/create")){
            return chain.filter(exchange);
        }
        Map<String, HttpCookie> stringHttpCookieMap = request.getCookies().toSingleValueMap();
        String token = stringHttpCookieMap.get("token").getValue();

        System.out.println(token);
        if(userService.validate(token) == false){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
